<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Admin\BaseController;
use App\Models\Renting;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Matrix\Exception;

class LoginController extends BaseController
{
    public function login(Request $request)
    {
        try {
            $data = $this->validate($request, [
                'username' => 'required',
                'password' => 'required'
            ]);
        } catch (\Exception $exception) {
            return response()->json(['status' => 1000, 'msg' => '用户名或密码不能为空'], 400);
        }
        // auth.php (config 文件件)里的webapi
        $bool = auth()->guard('webapi')->attempt($data);
        if ($bool == false) {
            return response()->json(['status' => 1001, 'msg' => '密码或账号错误'], 401);
        } else {
            // 得到登录成功的用户的模型
            $userModel = auth()->guard('webapi')->user();
            // 判断当前用户登录次数是否超上限
            if ($userModel->click > env('APINUM')) {
                return response()->json(['status' => 1002, 'msg' => '当天访问次数超上限'], 403);
            }
            // 点击次数加一    加一动作由数据库自己完成
            $userModel->increment('click');
            /**
             * 下面的两行会出现问题   多台机器同时请求会出现数据丢失  因为从数据库获取了数据,在本地完成加一动作再上传数据库
             * $click = $userModel->click + 1;
             * $userModel->update(['click' => $click]);
             */

            // 登录成功则生成token
            // 生成token  保存在服务器一份,返回给客户一份
            $token = $userModel->createToken($userModel->username)->accessToken;
            // 返回的数据
            $data = [
                'expire' => 7200,
                'token'  => $token
            ];
            return response()->json($data, 200);
        }
    }

    // 微信小程序登录
    public function wxlogin(Request $request)
    {
        $appid  = 'wx15b203a9a80ccf22';
        $secret = '51f88aed62522e6add485c6e8b864cbc';
        // 小程序传过来的
        $code = $request->get('code');
        // 请求地址
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $url = sprintf($url, $appid, $secret, $code);
        // 声明client请求客户端 并设置超时时间  verify 设置证书是否检查
        $client   = new Client(['timeout' => 5, 'verify' => false]);
        $response = $client->get($url);
        $ret      = (string)$response->getBody();
        // json转数组
        $arr = json_decode($ret, true);
        // 写入到数据表中renting  设置openid为 唯一检索
        try {
            Renting::create(['openid' => $arr['openid']]);
        } catch (\Exception $exception) {
        }
        return $ret;
    }
}
